# !/usr/bin python3
# encoding: utf-8 -*-
# @file     : notice_res.py
# @author   : 沙陌 Matongxue_2
# @Time     : 2023/8/8 21:00
# @Copyright: 北京码同学
import sys

import jsonpath
import requests

from common.file_load import load_yaml_file
from common.client import RequestsClient
from common.logger import GetLogger


class FeiShuNotice(RequestsClient):

    def __init__(self, job_name, build_number, result, user, build_url, url):
        # 'https://open.feishu.cn/open-apis/bot/v2/hook/b78ec614-0108-4a81-b752-6c4fe1d32eda'
        super().__init__()
        self.res = load_yaml_file('result.yml')
        self.url = url
        self.method = 'post'
        self.json = {
            "msg_type": "post",
            "content": {
                "post": {
                    "zh_cn": {
                        "title": f"{job_name}第{build_number}次测试完成",
                        "content": [
                            [{
                                "tag": "text",
                                "text": f"状态:{result}"
                            }],
                            [{
                                "tag": "text",
                                "text": f"用例总数:{self.res['total']}"
                            }],
                            [{
                                "tag": "text",
                                "text": f"成功:{self.res['passed']}"
                            }],
                            [{
                                "tag": "text",
                                "text": f"失败:{self.res['failed']}"
                            }],
                            [{
                                "tag": "text",
                                "text": f"跳过:{self.res['skipped']}"
                            }],
                            [{
                                "tag": "text",
                                "text": f"错误:{self.res['error']}"
                            }],
                            [{
                                "tag": "text",
                                "text": f"执行人:{user}"
                            }],
                            [{
                                "tag": "a",
                                "text": "查看报告",
                                "href": f"{build_url}/allure"
                            }],

                        ]
                    }
                }
            }
        }


class WxNotice(RequestsClient):

    def __init__(self, job_name, build_number, result, user, build_url, url):
        # 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=3d46a03b-8a7f-4eeb-a3c2-a1b379e4181f'
        super().__init__()
        self.res = load_yaml_file('result.yml')  # 加载结果文件
        self.url = url
        self.method = 'post'
        # 任务名称/构建次数/构建结果/测试用例统计（总数、通过、失败、错误、跳过）/执行人/报告链接
        self.json = {
            "msgtype": "markdown",
            "markdown": {
                "content": f"#### {job_name}测试完成  \n - 任务：第{build_number}次\n - 状态：{result} \n - 用例总数: {self.res['total']} \n - 成功: {self.res['passed']} \n - 失败: {self.res['failed']} \n - 错误: {self.res['error']} \n - 跳过: {self.res['skipped']} \n - 执行人: {user}  \n[查看报告]({build_url}/allure) "
            }
        }


class DingDingNotice(RequestsClient):

    def __init__(self, job_name, build_number, result, user, build_url, url):
        # 'https://oapi.dingtalk.com/robot/send?access_token=eda69535b902dfc3f009aba101c407cf11e1e68e758b194d4a232f42f1ad1aca'
        super().__init__()
        self.res = load_yaml_file('result.yml')
        self.url = url
        self.method = 'post'
        self.json = {
            "msgtype": "markdown",
            "markdown": {
                "title": f"### {job_name}测试完成",
                "text": f"### {job_name}测试完成 \n - 任务：第{build_number}次\n - 状态：{result} \n - 用例总数: {self.res['total']} \n - 成功: {self.res['passed']} \n - 失败: {self.res['failed']} \n - 错误: {self.res['error']} \n - 跳过: {self.res['skipped']} \n - 执行人: {user}  \n[查看报告]({build_url}/allure) "
            }
        }


class JenkinsStatus(RequestsClient):
    def __init__(self, build_url, username, password):
        super().__init__()
        self.url = f'{build_url}/api/json'
        self.method = 'get'
        self.session.auth = (username, password)  # 加到请求头上：


if __name__ == '__main__':
    GetLogger.get_logger('wx')

    args = sys.argv  # 表示获取终端执行时传递的参数
    build_url = args[1]  # http://服务器地址/job/项目名/构建号
    notice_type = args[2]  # 通知类型，是飞书还是钉钉还是企微
    username = args[3]  # jenkins 的账号
    password = args[4]  # jenkins 的密码
    url = args[5]  # 微信 钉钉 飞书 的webhook
    # job_name = 'apiautotest20230805'
    # build_number = 3
    # build_url = 'http://192.168.0.188:8080/job/apiautotest20230805/3'

    # 进行基本认证
    resp = JenkinsStatus(build_url, username, password).send()

    # 拿到响应结果的字段
    user = jsonpath.jsonpath(resp.json(), '$..shortDescription')[0]  # 获取触发构建的用户名和描述。 例子：由定时器触发构建
    result = jsonpath.jsonpath(resp.json(), '$..result')[0]  # 拿到的是构建的结果
    fullDisplayName = jsonpath.jsonpath(resp.json(), '$..fullDisplayName')[0]  # 项目名称+构建号  例子：apiautotest #1

    # apiautotest20230805 #3
    job_name = fullDisplayName.split(' #')[0]  # 项目名称
    build_number = fullDisplayName.split(' #')[1]  # 构建号

    # 根据不同的通知类型（notice_type）来发送构建结果通知
    if notice_type == 'wx':
        WxNotice(job_name, build_number, result, user, build_url, url).send()
    elif notice_type == 'dd':
        DingDingNotice(job_name, build_number, result, user, build_url, url).send()
    elif notice_type == 'feishu':
        FeiShuNotice(job_name, build_number, result, user, build_url, url).send()
